package com.wcgksoft.operation;

import com.aliyuncs.exceptions.ClientException;
import com.wcgksoft.common.util.aliyun.Sms;
import com.wcgksoft.common.util.comm.StringUtils;
import com.wcgksoft.entity.Alert.Alarm;
import com.wcgksoft.entity.Alert.AlarmHistory;
import com.wcgksoft.entity.ZData.*;
import com.wcgksoft.entity.dataAnalysis.DepartProjectData;
import com.wcgksoft.entity.dataAnalysis.Threshold;
import com.wcgksoft.service.BasicDataService;
import com.wcgksoft.service.DataAnalysis.ThresholdService;

import com.wcgksoft.service.alarm.AlarmHistoryService;
import com.wcgksoft.service.alarm.AlarmService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.util.*;

/**
 * 天气情况
 * 抓取温度（如果湿度也能抓取好），每天抓取5个时间的温度（早上8点，上午10点，中午12点，下午2点，傍晚4点，傍晚6点），并存到数据库中。
 *
 * @author 蒋世维
 */
public class alarmEml implements InitializingBean, ServletContextAware {

  @Autowired
  private ThresholdService thresholdService;

  @Autowired
  private AlarmService alarmService;

  @Autowired
  private BasicDataService basicDataServise;

  @Autowired
  private AlarmHistoryService alarmHistoryService;


  private Boolean Onred(Double s1, Double s2, String ors) {
    if (ors.equals(">")) {
      return s1 > s2;
    } else if (ors.equals("<")) {
      return s1 < s2;
    } else if (ors.equals(">=")) {
      return s1 >= s2;
    } else if (ors.equals("<=")) {
      return s1 <= s2;
    } else if (ors.equals("==")) {
      return s1 == s2;
    } else {
      return false;
    }
  }

  public void afterPropertiesSet() throws Exception {
    long timeInterval = 30 * 60 * 100;// 1小时的毫秒设定
    Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      public void run() {

        DetachedCriteria criteria = DetachedCriteria.forClass(Threshold.class);
        List<Threshold> all = thresholdService.findByConditions(criteria);
        for (Threshold threshold : all) {
          DepartProjectData departProjectData = threshold.getDepartProjectData();
          Alarm alarm;
          AlarmHistory alarmHistory = null;

          DetachedCriteria dataTemperature = DetachedCriteria.forClass(BasicData.class);
          dataTemperature.add(Restrictions.eq("datatype", departProjectData.getDataType().getD_key()));
          dataTemperature.add(Restrictions.eq("no", departProjectData.getEquipment().getE_number()));
          dataTemperature.add(Restrictions.eq("com", departProjectData.getCom()));
          dataTemperature.addOrder(Order.desc("Acquisitiontime"));
          List<BasicData> ztList;
          ztList = basicDataServise.findByConditions(dataTemperature);
          if (ztList.size() > 0) {
            ztList = ztList.subList(0, 1);
          } else {
            continue;
          }


          DetachedCriteria alarms = DetachedCriteria.forClass(Alarm.class);
          criteria.createAlias("departProjectData", "departProjectData");
          alarms.add(Restrictions.eq("departProjectData.id", departProjectData.getId()));
          List<Alarm> all1 = alarmService.findByConditions(alarms);





          if (all1.size() == 0) {
            alarm = new Alarm();
            alarm.setOnealarmtime(new Date());

          } else {
            alarm = all1.get(0);
          }


          if (ztList.stream().allMatch(element -> Onred(Double.valueOf(element.getData()), threshold.getGjfw(), threshold.getGjfwyz()))) {
            if (null!=alarm.getStitas()&&alarm.getStitas()==0){
              alarmHistory=new AlarmHistory();
              alarmHistory.setOnealarmtime(new Date());
              alarmHistory.setAlarmtime(ztList.get(0).getAcquisitiontime());
              alarmHistory.setTypecode(departProjectData.getDataType().getD_key());
              alarmHistory.setArname(departProjectData.getDataType().getD_name());
              alarmHistory.setCurrentvalue(Double.valueOf(ztList.get(0).getData()));
              alarmHistory.setNo(departProjectData.getEquipment().getE_number());
              alarmHistory.setCom(departProjectData.getCom());
              alarmHistory.setLevel("高级告警");
              alarmHistory.setStitas(1);
              alarmHistory.setSetvalue(threshold.getGjfw());
              alarmHistory.setEnterpriseid(departProjectData.getEnterpriseProject().getEnterprise().getId());
              alarmHistory.setDepartProjectData(departProjectData);
              alarmHistoryService.save(alarmHistory);
            }
            alarm.setAlarmtime(ztList.get(0).getAcquisitiontime());
            alarm.setTypecode(departProjectData.getDataType().getD_key());
            alarm.setArname(departProjectData.getDataType().getD_name());
            alarm.setCurrentvalue(Double.valueOf(ztList.get(0).getData()));
            alarm.setNo(departProjectData.getEquipment().getE_number());
            alarm.setCom(departProjectData.getCom());
            alarm.setLevel("高级告警");
            alarm.setStitas(1);
            alarm.setSetvalue(threshold.getGjfw());
            alarm.setEnterpriseid(departProjectData.getEnterpriseProject().getEnterprise().getId());
            alarm.setDepartProjectData(departProjectData);


            long time = alarm.getOnealarmtime().getTime();
            long now = new Date().getTime();
            long cha = now - time;
            double result = cha * 1.0 / (1000 * 60 * 60);
            if (result >= 5) {
              System.out.println("大于五小时");
              alarm.setOnealarmtime(new Date());
              try {
                if (null!=departProjectData.getPhone01()&&!departProjectData.getPhone01().equals("")) {
                  Sms.sendSms(departProjectData.getPhone01(), departProjectData.getEnterpriseProject().getEnterprise().getDepartName(), departProjectData.getDataType().getD_name(), ztList.get(0).getData());
                }
                if (null!=departProjectData.getPhone02()&&!departProjectData.getPhone02().equals("")) {
                  Sms.sendSms(departProjectData.getPhone02(), departProjectData.getEnterpriseProject().getEnterprise().getDepartName(), departProjectData.getDataType().getD_name(), ztList.get(0).getData());
                }
              } catch (ClientException e) {
                System.out.println("发送短信失败");
                e.printStackTrace();
              }
            } else {
              System.out.println("没超过五小时不进行短信报警！");
            }

            alarmService.saveOrUpdate(alarm);

          } else if (ztList.stream().allMatch(element -> Onred(Double.valueOf(element.getData()), threshold.getQwcb(), threshold.getQwcbyz()))) {
            if (null!=alarm.getStitas()&&alarm.getStitas()==0){
              alarmHistory=new AlarmHistory();
              alarmHistory.setOnealarmtime(new Date());
              alarmHistory.setDepartProjectData(departProjectData);
              alarmHistory.setAlarmtime(ztList.get(0).getAcquisitiontime());
              alarmHistory.setTypecode(departProjectData.getDataType().getD_key());
              alarmHistory.setArname(departProjectData.getDataType().getD_name());
              alarmHistory.setCurrentvalue(Double.valueOf(ztList.get(0).getData()));
              alarmHistory.setLevel("中级告警");
              alarmHistory.setStitas(1);
              alarmHistory.setNo(departProjectData.getEquipment().getE_number());
              alarmHistory.setCom(departProjectData.getCom());
              alarmHistory.setSetvalue(threshold.getGjfw());
              alarmHistory.setEnterpriseid(departProjectData.getEnterpriseProject().getEnterprise().getId());
              alarmHistoryService.save(alarmHistory);
            }
            alarm.setDepartProjectData(departProjectData);
            alarm.setAlarmtime(ztList.get(0).getAcquisitiontime());
            alarm.setTypecode(departProjectData.getDataType().getD_key());
            alarm.setArname(departProjectData.getDataType().getD_name());
            alarm.setCurrentvalue(Double.valueOf(ztList.get(0).getData()));
            alarm.setLevel("中级告警");
            alarm.setStitas(1);
            alarm.setNo(departProjectData.getEquipment().getE_number());
            alarm.setCom(departProjectData.getCom());
            alarm.setSetvalue(threshold.getGjfw());
            alarm.setEnterpriseid(departProjectData.getEnterpriseProject().getEnterprise().getId());

            long time = alarm.getOnealarmtime().getTime();
            long now = new Date().getTime();
            long cha = now - time;
            double result = cha * 1.0 / (1000 * 60 * 60);
            if (result >= 5) {
              System.out.println("大于五小时");
              alarm.setOnealarmtime(new Date());
              try {
                if (null!=departProjectData.getPhone01()&&!departProjectData.getPhone01().equals("")) {
                  Sms.sendSms(departProjectData.getPhone01(), departProjectData.getEnterpriseProject().getEnterprise().getDepartName(), departProjectData.getDataType().getD_name(), ztList.get(0).getData());
                }
                if (null!=departProjectData.getPhone02()&&!departProjectData.getPhone02().equals("")) {
                  Sms.sendSms(departProjectData.getPhone02(), departProjectData.getEnterpriseProject().getEnterprise().getDepartName(), departProjectData.getDataType().getD_name(), ztList.get(0).getData());
                }
              } catch (ClientException e) {
                System.out.println("发送短信失败");
                e.printStackTrace();
              }
            } else {
              System.out.println("没超过五小时不进行短信报警！");
            }
            alarmService.saveOrUpdate(alarm);
          } else if (!ztList.stream().allMatch(element -> Onred(Double.valueOf(element.getData()), threshold.getGjfw(), threshold.getGjfwyz())) && !ztList.stream().allMatch(element -> Onred(Double.valueOf(element.getData()), threshold.getQwcb(), threshold.getQwcbyz()))) {
            alarm.setDepartProjectData(departProjectData);
            alarm.setAlarmtime(ztList.get(0).getAcquisitiontime());
            alarm.setTypecode(departProjectData.getDataType().getD_key());
            alarm.setArname(departProjectData.getDataType().getD_name());
            alarm.setCurrentvalue(Double.valueOf(ztList.get(0).getData()));
            alarm.setLevel("正常");
            alarm.setStitas(0);
            alarm.setNo(departProjectData.getEquipment().getE_number());
            alarm.setCom(departProjectData.getCom());
            alarm.setSetvalue(threshold.getGjfw());
            alarm.setEnterpriseid(departProjectData.getEnterpriseProject().getEnterprise().getId());
            alarmService.saveOrUpdate(alarm);
          } else {
            System.out.println("正常");
          }


        }
      }
    }, 60000, 120000);//定的定时器在15:10分开始执行,每隔 1小时执行一次.

  }

  @Override
  public void setServletContext(ServletContext arg0) {


  }


}
